<template>
  <div>
    <h2>异常告警管理</h2>
    
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-select v-model="alertStatus" placeholder="告警状态" clearable>
          <el-option label="全部" value="" />
          <el-option label="活跃" value="active" />
          <el-option label="已解决" value="resolved" />
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-select v-model="alertType" placeholder="告警类型" clearable>
          <el-option label="全部类型" value="" />
          <el-option label="pH异常" value="ph_anomaly" />
          <el-option label="湿度异常" value="moisture_anomaly" />
          <el-option label="SOC下降" value="soc_decrease" />
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card>
          <template #header>
            <span>告警统计</span>
          </template>
          <div class="stat-item">
            <span class="stat-label">总告警数</span>
            <span class="stat-value">{{ alertStats.total }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">活跃告警</span>
            <span class="stat-value error">{{ alertStats.active }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">今日新增</span>
            <span class="stat-value warning">{{ alertStats.today }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card>
          <template #header>
            <span>告警类型分布</span>
          </template>
          <v-chart :option="alertTypeChart" style="height: 200px" />
        </el-card>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>告警列表</span>
          </template>
          <el-table :data="alertList" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="告警ID" width="100" />
            <el-table-column prop="type" label="类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getAlertTypeTag(row.type)">{{ getAlertTypeText(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="message" label="告警信息" min-width="300" />
            <el-table-column prop="severity" label="严重程度" width="100">
              <template #default="{ row }">
                <el-tag :type="getSeverityType(row.severity)">{{ row.severity }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="plot_id" label="地块ID" width="100" />
            <el-table-column prop="timestamp" label="时间" width="180" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'danger' : 'success'">
                  {{ row.status === 'active' ? '活跃' : '已解决' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button 
                  v-if="row.status === 'active'" 
                  type="text" 
                  size="small"
                  @click="handleResolve(row)"
                >
                  标记解决
                </el-button>
                <el-button type="text" size="small" @click="handleDetail(row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 告警详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="告警详情"
      width="600px"
    >
      <div v-if="selectedAlert">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="告警ID">{{ selectedAlert.id }}</el-descriptions-item>
          <el-descriptions-item label="告警类型">{{ getAlertTypeText(selectedAlert.type) }}</el-descriptions-item>
          <el-descriptions-item label="严重程度">{{ selectedAlert.severity }}</el-descriptions-item>
          <el-descriptions-item label="地块ID">{{ selectedAlert.plot_id }}</el-descriptions-item>
          <el-descriptions-item label="告警时间">{{ selectedAlert.timestamp }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ selectedAlert.status === 'active' ? '活跃' : '已解决' }}</el-descriptions-item>
        </el-descriptions>
        <el-divider />
        <h4>告警信息</h4>
        <p>{{ selectedAlert.message }}</p>
        <el-divider />
        <h4>处理建议</h4>
        <p>{{ getSuggestion(selectedAlert.type) }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const alertStatus = ref('')
const alertType = ref('')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(50)
const showDetailDialog = ref(false)
const selectedAlert = ref(null)

const alertStats = ref({
  total: 50,
  active: 12,
  today: 3
})

const alertTypeChart = ref({
  tooltip: { trigger: 'item' },
  series: [{
    type: 'pie',
    radius: '50%',
    data: [
      { value: 20, name: 'pH异常' },
      { value: 15, name: '湿度异常' },
      { value: 10, name: 'SOC下降' },
      { value: 5, name: '其他' }
    ]
  }]
})

const alertList = ref([
  {
    id: 'ALT001',
    type: 'ph_anomaly',
    message: '地块P001 pH值异常：当前值5.2，正常范围6.0-7.5',
    severity: 'high',
    timestamp: '2024-11-11 15:30:00',
    plot_id: 'P001',
    status: 'active'
  },
  {
    id: 'ALT002',
    type: 'moisture_low',
    message: '地块P003 土壤湿度偏低：当前值12%，建议灌溉',
    severity: 'medium',
    timestamp: '2024-11-11 14:15:00',
    plot_id: 'P003',
    status: 'active'
  },
  {
    id: 'ALT003',
    type: 'soc_decrease',
    message: '地块P005 SOC含量持续下降，建议增施有机肥',
    severity: 'low',
    timestamp: '2024-11-11 10:20:00',
    plot_id: 'P005',
    status: 'resolved'
  }
])

const getAlertTypeTag = (type) => {
  const tags = {
    ph_anomaly: 'danger',
    moisture_anomaly: 'warning',
    soc_decrease: 'info'
  }
  return tags[type] || 'default'
}

const getAlertTypeText = (type) => {
  const texts = {
    ph_anomaly: 'pH异常',
    moisture_anomaly: '湿度异常',
    soc_decrease: 'SOC下降'
  }
  return texts[type] || type
}

const getSeverityType = (severity) => {
  const types = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return types[severity] || 'default'
}

const getSuggestion = (type) => {
  const suggestions = {
    ph_anomaly: '建议检测土壤酸碱性，必要时施用石灰或硫磺粉调节pH值',
    moisture_low: '建议及时灌溉，保持土壤湿度在适宜范围内',
    soc_decrease: '建议增施有机肥，提高土壤有机质含量'
  }
  return suggestions[type] || '请根据具体情况采取相应措施'
}

const handleSearch = () => {
  loading.value = true
  // 模拟搜索
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const handleReset = () => {
  alertStatus.value = ''
  alertType.value = ''
  handleSearch()
}

const handleResolve = (row) => {
  ElMessageBox.confirm(
    `确定要将告警 ${row.id} 标记为已解决吗？`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    // 模拟标记解决
    row.status = 'resolved'
    ElMessage.success('操作成功')
  })
}

const handleDetail = (row) => {
  selectedAlert.value = row
  showDetailDialog.value = true
}

const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

onMounted(() => {
  handleSearch()
})
</script>

<style scoped>
.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 5px 0;
}

.stat-label {
  color: #606266;
}

.stat-value {
  font-weight: bold;
  font-size: 18px;
}

.error {
  color: #F56C6C;
}

.warning {
  color: #E6A23C;
}
</style>
